import { onMounted, onBeforeUnmount, ref, Ref } from 'vue';
import { Html5Qrcode } from 'html5-qrcode';

export function useScan() {
  const scanResult = ref('');
  const html5QrCode: Ref<Html5Qrcode | null> = ref(null);
  const qrCodeReader: Ref<HTMLElement | null> = ref(null); // 模板引用

  const onScanSuccess = (decodedText: string) => {
    scanResult.value = decodedText;
    stopScan();
  };

  const onScanFailure = (error: any) => {
    console.warn('扫描失败:', error);
  };

  const startScan = async () => {
    try {
      if (qrCodeReader.value) {
        html5QrCode.value = new Html5Qrcode(qrCodeReader.value.id);
        await html5QrCode.value.start(
          { facingMode: 'environment' },
          {
            fps: 10, // 扫描帧率
            qrbox: { width: 250, height: 250 } // 扫描框大小:cite[4]
          },
          onScanSuccess
        );
      }
    } catch (err: any) {
      console.error('无法启动扫码，请检查摄像头权限或HTTPS环境:', err);
    }
  };

  // 停止扫描
  const stopScan = async () => {
    if (html5QrCode.value) {
      try {
        await html5QrCode.value.stop();
        html5QrCode.value.clear(); // 清理资源
        html5QrCode.value = null;
      } catch (err: any) {
        console.error('停止扫码器时出错:', err);
      }
    }
  };

  // 组件挂载时开始扫描
  onMounted(() => {
    startScan();
  });

  // 组件卸载前务必停止扫描，释放摄像头
  onBeforeUnmount(() => {
    stopScan();
  });

  return { scanResult, qrCodeReader, startScan, stopScan };
}
